<template>
  <div class="img">
    <a-upload
      name="file"
      listType="picture-card"
      :multiple="isMultiple"
      :accept="accept"
      :action="uploadAction"
      :headers="headers"
      :data="{biz:bizPath,watermark:watermark,bl:bl}"
      :fileList="fileList"
      :before-upload="beforeUpload"
      :disabled="disabled"
      :isMultiple="isMultiple"
      @change="handleChange"
      @preview="handlePreview"
      :class="[!isMultiple?'imgupload':'', (!isMultiple && picUrl)?'image-upload-single-over':'' ]">
      <div>
        <!--<img v-if="!isMultiple && picUrl" :src="getAvatarView()" style="width:100%;height:100%"/>-->
        <div class="iconp">
          <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
          <div class="ant-upload-text">{{ text }}</div>
        </div>
      </div>
      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel()">
        <!--<img alt="example" style="width: 100%" :src="previewImage"/>-->
        <video width="100%" controls id="video">
          <source :src="previewImage" type="video/mp4"/>
          <object :data="previewImage" width="100%">
            <embed :src="previewImage" width="100%"/>
          </object>
        </video>
      </a-modal>
    </a-upload>

    <div v-show="false">
      <div v-if="fileList&&fileList[0]">
        <video controls="controls" style="height: 100px;width: 100px;"  id="up-video">您的浏览器不支持视频播放</video>
      </div>
      <canvas id="my-canvas" style="display: none"></canvas>
    </div>
    <!--封面图--->
    <div v-if="coverList && coverList.length>0" class="circle">
      <ul class="circle-ul">
        <li v-for="(item) of coverList"  class="circle-li">
          <div v-on:click="changeList(getFileUrl(item))" :class="getFileUrl(item)==a?'op1':'op2'" class="changeBorder" value="change!">
            <img :src="getFileUrl(item)" style="width: 100px;height: 100px;" alt  />
            <div class="topic-shade" :class="getFileUrl(item)==a?'img1':'img2'">
              <div class="shade"><img src="@/assets/check-box.png" style="width: 14px;height: 14px;" alt /></div>
            </div>
          </div>
        </li>
      </ul>
    </div>

    <j-image-open ref="imagePreview"></j-image-open>
  </div>
</template>

<script>
  import Vue from 'vue'
  import { ACCESS_TOKEN } from "@/store/mutation-types"
  import { getFileAccessHttpUrl } from '@/api/manage'
  import JImageOpen from './JImageOpen'

  const uidGenerator=()=>{
    return '-'+parseInt(Math.random()*10000+1,10);
  }
  const getFileName=(path)=>{
    if(path.lastIndexOf("\\")>=0){
      let reg=new RegExp("\\\\","g");
      path = path.replace(reg,"/");
    }
    return path.substring(path.lastIndexOf("/")+1);
  }
  export default {
    name: 'JVideoUpload',
    components: {
      JImageOpen
    },
    data(){
      return {
        uploadAction:window._CONFIG['domianURL']+"/sys/common/upload",
        //uploadAction:"http://192.168.31.153:8010/jeecg-boot/sys/common/upload",
        uploadLoading:false,
        picUrl:false,
        headers:{},
        fileList: [],
        coverList: [],
        previewImage:"",
        previewVisible: false,
        coverSrc:'',
        a:true,
      }
    },
    props:{
      coverImg:{
        type:String,
        required:false,
        default:""
      },
      accept: {
        type: String,
        required:false,
        default: ""
      },
      imgList:{
        type:Array,
        required:false,
        default:function () { return [] }
      },
      text:{
        type:String,
        required:false,
        default:"视频上传"
      },
      /*这个属性用于控制文件上传的业务路径*/
      bizPath:{
        type:String,
        required:false,
        default:"temp"
      },
      /*这个属性用于控制文件上传是否添加水印*/
      watermark:{
        type:String,
        required:false,
        default:"false"
      },
      /*这个属性用于控制图片上传宽高比例*/
      bl:{
        type:String,
        required:false,
        default:""
      },
      value:{
        type:[String,Array],
        required:false
      },
      disabled:{
        type:Boolean,
        required:false,
        default: false
      },
      isMultiple:{
        type:Boolean,
        required:false,
        default: false
      },
      //update-begin-author:wangshuai date:20201021 for:LOWCOD-969 新增number属性，用于判断上传数量
      number:{
        type:Number,
        required:false,
        default:0
      }
      //update-end-author:wangshuai date:20201021 for:LOWCOD-969 新增number属性，用于判断上传数量
    },
    watch:{
      value: {
        handler(val,oldValue) {
          if (val instanceof Array) {
            this.initFileList(val.join(','))
          } else {
            this.initFileList(val)
          }
          if(!val || val.length==0){
            this.picUrl = false;
          }
        },
        //立刻执行handler
        immediate: true
      },
      imgList:{
        handler(val) {
          if(val){
            this.coverList = val;
          }
        },
      },
      coverImg:{
        handler(val) {
          if(val){
            this.coverImg = val;
            this.changeList(this.getFileUrl(val));
          }


        },
      },
      previewVisible:function (val) {
        console.log('监听弹层是否打开，关闭视频',this.previewVisible)
        if(this.previewVisible === false){
          let my_video = document.getElementById("video")
          my_video.pause();
        }
      },

    },
    created(){
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token":token}
      console.log(this.model)
    },
    methods:{
      changeList(id){
        if(this.a == id){
          let o = {coverImg:''}
          this.$emit('success', o);
          this.a =! this.a;
        }else{
          let o = {coverImg:id}
          this.$emit('success', o);
          this.a =id;
        }
      },
      getFileUrl(url){
        return getFileAccessHttpUrl(url);
        /* if(url.indexOf("http://192.168.31.153:9000/")<0){
           return 'http://192.168.31.153:9000/'+url;
         }
         return url;*/
      },
      //截取视频第一帧作为播放前默认图片
      getVideoCover(url) {

        url = this.getFileUrl(url);
        //console.log(url);
        const video = document.getElementById("up-video"); // 获取视频对象
        video.src = url; // url地址 url跟 视频流是一样的
        console.log(video)
        var canvas = document.getElementById("my-canvas"); // 获取 canvas 对象
        const ctx = canvas.getContext("2d"); // 绘制2d
        video.crossOrigin = "anonymous"; // 解决跨域问题，也就是提示污染资源无法转换视频
        video.currentTime = 1; // 第十帧
        video.oncanplay = () => {
          canvas.width = 100;//video.clientWidth; // 获取视频宽度
          canvas.height = 100;//video.clientHeight; //获取视频高度
          // 利用canvas对象方法绘图
          ctx.drawImage(video, 0, 0, 100, 100);
          // 转换成base64形式
          this.coverSrc = canvas.toDataURL("image/png"); // 截取后的视频封面
          //console.log(this.coverSrc);
          let itemIcon = document.getElementsByClassName("ant-upload-list-item-icon");
          let uploadItemIcon = itemIcon[itemIcon.length - 1];
          uploadItemIcon.style.opacity=0;
          let itemInfo = document.getElementsByClassName("ant-upload-list-item-info");
          let uploadItemInfo = itemInfo[itemInfo.length - 1];
          uploadItemInfo.style.backgroundImage=`url(${this.coverSrc})`;
        };
      },

      initFileList(paths){
        if(!paths || paths.length==0){
          this.fileList = [];
          return;
        }
        this.picUrl = true;
        let fileList = [];
        let arr = paths.split(",")
        for(var a=0;a<arr.length;a++){
          let url = this.getFileUrl(arr[a]);
          fileList.push({
            uid: uidGenerator(),
            name: getFileName(arr[a]),
            status: 'done',
            url: url,
            response:{
              status:"history",
              message:arr[a]
            }
          })
        }
        this.fileList = fileList
      },

      beforeUpload:function(file){
        return new Promise((resolve, reject) => {
          let str = file.name.replace(/.+\./, "");
          const isImage = file.type.indexOf('video')==0;
          if(!isImage){
            if(str!=='DAT'&&str!=='rmvb'&&str!=='dat'&&str!=='mp4'&&str!=='rm'&&str!=='wmv9'&&str!=='flv'&&str!=='asx'&&str!=='asf'
               &&str!=='mov'&&str!=='3gp'&&str!=='wmv'&&str!=='mpg'&&str!=='avi'){
              this.$message.warning('请上传视频格式文件！');
              return false;
            }
          }
          if (isImage||str==='DAT'||str==='rmvb'||str==='dat'||str==='mp4'||str==='rm'||str==='wmv9'||str==='flv'||str==='asx'||str==='asf'
            ||str==='mov'||str==='3gp'||str==='wmv'||str==='mpg'||str==='avi') {
            this.picUrl = true;
            let reader = new FileReader(); //这个是通过原生的方式来获取图片的宽高
            reader.readAsDataURL(file);
            reader.onload = () => {
              return resolve(true)
            }
          }
        });

      },
      handleChange(info) {
        this.picUrl = true;
        let fileList = info.fileList
        console.log(info)
        //update-begin-author:wangshuai date:20201022 for:LOWCOD-969 判断number是否大于0和是否多选，返回选定的元素。
        if(this.number>0 && this.isMultiple){
          fileList = fileList.slice(-this.number);
        }
        //update-end-author:wangshuai date:20201022 for:LOWCOD-969 判断number是否大于0和是否多选，返回选定的元素。
        if(info.file.status==='done'){
          if(info.file.response.success){
            this.picUrl = true;
            fileList = fileList.map((file) => {
              if (file.response) {
                let  res = file.response.message;
                file.url = getFileAccessHttpUrl(res);
              }
              return file;
            });
          }
          //this.$message.success(`${info.file.name} 上传成功!`);
        }else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`);
        }else if(info.file.status === 'removed'){
          this.handleDelete(info.file)
        }
        this.fileList = fileList
        if(info.file.status==='done' || info.file.status === 'removed'){
          this.handlePathChange()
        }
      },
      // 预览
      handlePreview (file) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
        //this.$refs.imagePreview.imageOpen(file.url || file.thumbUrl);
      },
      // 预览
      coverOpen(file) {
        this.$refs.imagePreview.imageOpen(file);
      },
      getAvatarView(){
        if(this.fileList.length>0){
          let url = this.fileList[0].url
          return this.getFileUrl(url)
        }
      },
      handlePathChange(){
        let uploadFiles = this.fileList
        let path = ''
        if(!uploadFiles || uploadFiles.length==0){
          path = ''
        }
        let arr = [];
        if(!this.isMultiple && uploadFiles.length>0){
          let res = uploadFiles[uploadFiles.length-1].response.message;
          arr.push(this.getFileUrl(res))
          window["that"]=this;
          setTimeout(function(){
            that.$emit('success', res);
            //that.$set(that,'coverList',res);
            // this.coverSrc = this.coverList[0];
          }, 2000);
          //res.imgList='';
        }else{
          for(let a=0;a<uploadFiles.length;a++){
            // update-begin-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
            if(uploadFiles[a].status === 'done' ) {
              arr.push(this.getFileUrl(res.newvideo))
              console.log(uploadFiles[a].response);
              //arr.push(uploadFiles[a].response.message)
            }else{
              return;
            }
            // update-end-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
          }
        }
        if(arr.length>0){
          path = arr.join(",")
        }
        let url = arr[(arr.length)-1];
        const video = document.getElementById("up-video"); // 获取视频对象
        video.src = url; // url地址 url跟 视频流是一样的
        this.previewImage = url
        //this.getVideoCover(url);
        this.$emit('change', path);
      },
      handleDelete(file){
        //如有需要新增 删除逻辑
        let mod ={
          coverImg:"",
          imgList:[],
          min:0,
          name:'',
          newvideo:'',
          oldvideo:'',
          time:'',
          uuid:'',
          flag:'0'
        };
        this.$set(this,'coverList',[]);
        this.$emit('success', mod);
        this.picUrl = false;
        console.log(file)
      },
      handleCancel() {
        this.close();
        this.previewVisible = false;
      },
      close () {

      },
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style scoped>
  /* update--begin--autor:lvdandan-----date:20201016------for：j-image-upload图片组件单张图片详情回显空白
  * https://github.com/zhangdaiscott/jeecg-boot/issues/1810
  * https://github.com/zhangdaiscott/jeecg-boot/issues/1779
  */

  /deep/ .imgupload .iconp{padding:20px;}
  /* update--end--autor:lvdandan-----date:20201016------for：j-image-upload图片组件单张图片详情回显空白*/

  /deep/ .image-upload-single-over .ant-upload-select{display: none}
  .ant-upload-text{
    width: 70px;
  }
  /*/deep/
  .ant-upload-list-item-info{
    background-image: url("");
  }*/


  .circle{
    position: relative;
    width: 730px;
    left: -46px;
  }
  .circle-ul {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    width: 532px;
    padding: 0;
    margin: 14px 0 0 50px;
  }
  .circle-li {
    width: 114px;
    height: 114px;
    margin-right: 10px;
    list-style: none;
    margin-bottom: 20px;
  }
  .topic-shade{
    display: none;
  }
  .img1{
    opacity: 1;
  }
  .img2{
    opacity: 0;
  }
  .changeBorder{
    width: 100%;
    height: 100%;
    position: relative;
    cursor: pointer;
    border: 1px dashed #969696;
    margin: -1px -8px 0 -8px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .op1{
    border-color: #969696;
  }
  .op2{
    border-color: rgba(0,0,0,0);
  }
  .topic-shade{
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    position: absolute;
    top: 123.5px;
    right: 0;
    bottom: 0;
    left: 86px;
  }

  .shade{
    margin-bottom: 4px;
  }

  /deep/
  .ant-upload-list-item-icon{
    opacity: 0;
  }
  /deep/
  .ant-upload-list-item-info{
    background: url(~@/assets/video.png)  no-repeat;
    background-size: 86px 86px;
  }
</style>
